package model

import (
	"errors"
	"gorm.io/gorm"
	"ppa/init/mysql"
)

type User struct {
	ID uint `json:"id" form:"user_id" gorm:"primaryKey;autoIncrement;not null"`
	UserName string `json:"user_name"  form:"user_name" gorm:"default:''"`
	UserAvatar string `json:"user_avatar" form:"user_avatar"  gorm:"default:''"`
	WalletAddress string `json:"wallet_address" form:"wallet_address"  gorm:"unique;size:256"`
	RegisterTime uint `json:"register_time" gorm:"autoCreateTime"`
	LastTime uint `json:"last_time" gorm:"autoUpdateTime"`
}

// GetUserInfo 通过钱包地址等信息查询用户
func (user *User)GetUserInfo() (*User, error)  {
	var UserInfo *User
	err := mysql.SqlDB.Where(user).First(&UserInfo).Error
	if err != nil || errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("未查询到数据存在")
	}
	return UserInfo, nil
}

// SetUserInfo 创建一个新的用户
func (user *User)SetUserInfo() (*User, error)  {
	err := mysql.SqlDB.Create(&user).Error
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// SetUserInfoByWalletAddress 更新用户信息通过钱包地址
func (user *User)SetUserInfoByWalletAddress() (*User, error)  {
	var resData *User
	err := mysql.SqlDB.Model(&resData).Omit("wallet_address","register_time","last_time").Where("wallet_address = ?",user.WalletAddress).Updates(user).Error
	if err != nil {
		return nil, err
	}
	return nil, nil
}